package com.example.wendao.view.viewholder;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.ImgUtils;
import com.example.wendao.common.PageUtils;
import com.example.wendao.common.ViewHolderBind;
import com.example.wendao.model.entity.News;
import com.example.wendao.model.entity.NewsPics;
import com.example.wendao.model.entity.User;
import com.example.wendao.viewmodel.NewsViewModel;
import com.example.wendao.viewmodel.UserViewModel;

public class NewsListViewHolder extends RecyclerView.ViewHolder implements ViewHolderBind<News> {

    private TextView newsTitleTV;
    private TextView forumTimeTV;
    private TextView forumAgreeTV;
    private ImageView forumImagIV;
    private NewsViewModel newsViewModel;
    private UserViewModel userViewModel;
    private TextView tvUsername;
    private TextView forum_agree_textview;

    public NewsListViewHolder(@NonNull ViewGroup viewGroup) {
        super(PageUtils.inflateItemView(viewGroup, R.layout.news_item));
        newsTitleTV = itemView.findViewById(R.id.news_title_textview);
        forumTimeTV = itemView.findViewById(R.id.forum_time_textview);
        forumAgreeTV = itemView.findViewById(R.id.forum_agree_textview);
        forumImagIV = itemView.findViewById(R.id.forum_imag_imagview);
        tvUsername = itemView.findViewById(R.id.tv_username);
        forum_agree_textview = itemView.findViewById(R.id.forum_agree_textview);
        newsViewModel = new ViewModelProvider(App.getInstance()).get(NewsViewModel.class);
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
    }

    @Override
    public void bindTo(News news) {
        User user = userViewModel.getUserById(news.getNewsAuthorId());
        newsTitleTV.setText(news.getNewsTitle());
        forumTimeTV.setText(news.getNewsTime());
        forumAgreeTV.setText(String.valueOf(news.getNewsAgree()));
        tvUsername.setText("作者:" + user.getUsername()); // 用户名
        forum_agree_textview.setText("" + news.getNewsAgree());
        NewsPics pics = newsViewModel.getCoverByNewId(news.getNewsId());
        if (pics != null){
            Bitmap bm = ImgUtils.barrayToBitmap(pics.getNewsPic());
            forumImagIV.setImageBitmap(bm);
        }
        itemView.setOnClickListener(v -> {
            int newsId = news.getNewsId();
            Bundle bundle = new Bundle();
            bundle.putInt("newId", newsId);
            bundle.putInt("userId", user.getUserId());
            Navigation.findNavController(v).navigate(R.id.action_fragment_new_to_fragment_news_detail, bundle);
        });
    }
}

